import React from 'react';
import './index.css'
import mzsdk from '../../../../utils/mzsdk'

import { replaceEm } from '../EmojiManager';

/**
 * 二分屏聊天列表
 */

// 记录上次请求数据的scrollHeight
var oldScrollHeight = 0;
// 是否正在请求中
var isLoading = false;

export default class ChatList extends React.Component {
    constructor(props) {
        super(props)
        // 是否自动滑动到底部
        this.state = {
            autoScrollToBottom: true
        }
    }

    componentDidMount() {
        var _this = this;
        mzsdk.mzee.on("chat_updateFrame", function () {
            _this.fixViewFrame()
        })

        mzsdk.mzee.on("chat_updateList", function () {
            _this.updateList()
        })

        mzsdk.mzee.on("requestHistoryFinishedToSetOffsetTop", function () {
            setTimeout(() => {
                isLoading = false
            }, 500);
            var chatBackground = document.getElementById('chatlist-wrapper')
            if (oldScrollHeight != chatBackground.scrollHeight) {
                if (oldScrollHeight == 0) {
                    return;
                }
                chatBackground.scrollTop = chatBackground.scrollHeight - oldScrollHeight
            }
        })

        this.fixViewFrame();

        this.onScrollToRequestHistoryOldMsg()
    }

    // 监听请求更多的历史消息记录
    onScrollToRequestHistoryOldMsg = () => {
        var _this = this;
        var chatBackground = document.getElementById('chatlist-wrapper')
        chatBackground.onscroll = function (e) {
            if (isLoading == false && chatBackground.scrollTop <= 0) {
                // 请求聊天历史数据，关闭自动滚动到底部功能
                _this.setState({
                    autoScrollToBottom: false
                })
                isLoading = true
                mzsdk.mzee.emit('toRequestHistoryOldMsg')
                oldScrollHeight = chatBackground.scrollHeight
            }
            if (chatBackground.scrollTop + chatBackground.clientHeight >= chatBackground.scrollHeight) {
                // 滑动底部了，开启自动滚动到底部功能
                _this.setState({
                    autoScrollToBottom: true
                })
            }
        }
    }

    componentWillUnmount() {
        mzsdk.mzee.off('chat_updateFrame')
        mzsdk.mzee.off('chat_updateList')
        mzsdk.mzee.off('requestHistoryFinishedToSetOffsetTop')
    }

    componentDidUpdate() {
        if (this.state.autoScrollToBottom == true) {
            this.scrollToEnd();
        }
    }

    updateList = () => {
        this.forceUpdate();
    }

    scrollToEnd = (isAnimation) => {
        const mzMessageListEndRef = document.getElementById("mzMessageListEndRef");
        if (isAnimation == true) {
            mzMessageListEndRef.scrollIntoView({ behavior: "smooth" });//带动画
        } else {
            mzMessageListEndRef.scrollIntoView();//不带动画
        }
    }

    fixViewFrame = () => {
        let window_height = window.innerHeight

        var video = document.getElementById('main-top-video-super-background')
        var rollingView = document.getElementById('rolling-ad-background')
        var menuView = document.getElementById('tab-menu-background')
        var interactionControl = document.getElementById('interaction-control-bar-background')
        var recommend = document.getElementById('mobile-main-goodDetail-recommend')
        var liveNotice = document.getElementById('live-notice-background')

        if (!video || !rollingView || !menuView || !interactionControl || !recommend || !liveNotice) {
            return;
        }

        let height = (window_height - video.clientHeight - rollingView.clientHeight - menuView.clientHeight - interactionControl.clientHeight - recommend.clientHeight - liveNotice.clientHeight - 1) + 'px'
        var chatBackground = document.getElementById('chatlist-wrapper')
        if (chatBackground) {
            chatBackground.style.height = height
        }

        this.updateList()
    }

    render() {
        let { list } = this.props;
        return (<ul className="chatlist-wrapper" id="chatlist-wrapper" style={{ padding: '0 0.2rem', margin: '0' }}>
            {
                list.map((item, index) => {
                    return (<li className="msg-caption" key={`chatlist-item-${index}`}>
                        <img className="user-host" src={item.avatar ? item.avatar : "//s1.zmengzhu.com/web/wap/img/default-avatar.jpg"} onClick={() => mzsdk.mzee.emit('onClick_userInfo', item)} />
                        <h3 className="user-name" style={{ maxWidth: '2.8rem' }}>{item.userName}</h3>
                        <p className="time">{item.time}</p>
                        {(() => {
                            switch (item.type) {
                                case 'gift':
                                    return <div className="msg-content-gift-background isSelf">
                                        <div className="msg-content-gift">
                                            <div className="msg-content-gift-name">送上{item.giftName}</div>
                                            <img className="msg-content-gift-icon" src={item.giftIcon}></img>
                                            <div className="msg-content-gift-quantity">x{item.giftQuantity}</div>
                                        </div>
                                    </div>
                                case 'text':
                                    return <div className="msg-content isSelf" dangerouslySetInnerHTML={{ __html: replaceEm(item.text) || '' }}></div>;
                                default:
                                    return <div className="msg-content isSelf">暂不支持该消息类型</div>;
                            }
                        })()}
                    </li>)
                })
            }
            <div id="mzMessageListEndRef"></div>
            {
                this.state.autoScrollToBottom == false && <div className="toEnd" onClick={() => { this.scrollToEnd(true); }}>滑到最底部</div>
            }
        </ul>);
    }
}
